package com.test.daily.leetcode.y2022.m05.day0522.v09;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @descriptions:
 * @author: Tom
 * @date: 2022/5/22 下午 11:12
 * @version: 1.0
 */
public class Solution {
    public static class Node{
        int value;
        Node left;
        Node right;
        public Node(int value){
            this.value = value;
        }
    }
    public static boolean isCBT1(Node root){
        if(root == null){
            return true;
        }
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        boolean leaf = false;
        while(!queue.isEmpty()){
            Node l = root.left;
            Node r = root.right;
            if(leaf && (root.left != null || root.right !=null)
            || (root.left == null || root.right != null)){
                return false;
            }
            if(l != null){
                queue.add(l);
            }
            if(r != null){
                queue.add(r);
            }
            if(l == null || r == null){
                leaf = true;
            }
        }
        return true;
    }
    public static class Info{
        public boolean isCBT;
        public boolean isFull;
        public int height;
        public Info(boolean isCBT,boolean isFull, int height){
            this.isCBT = isCBT;
            this.isFull = isFull;
            this.height = height;
        }
    }
    public static boolean isCBT2(Node root){
       return process(root).isFull;
    }
    public static Info process(Node root){
        if(root == null){
            return new Info(true, true,0);
        }
        boolean isCBT = false;
        boolean isFull = false;
        Info leftInfo = process(root.left);
        Info rightInfo = process(root.right);
        int height = Math.max(leftInfo.height, rightInfo.height) + 1;
        if(leftInfo.isFull && rightInfo.isFull && leftInfo.height == rightInfo.height){
            isFull = true;
            isCBT = true;
        }
        if(isFull){
            isCBT = true;
        } else if(leftInfo.isCBT && rightInfo.isCBT) {
            if(leftInfo.isCBT && rightInfo.isFull && (leftInfo.height == rightInfo.height + 1)) {
                isCBT = true;
            } else if(leftInfo.isFull && rightInfo.isFull && (leftInfo.height == rightInfo.height + 1)){
                isCBT = true;
            } else if(leftInfo.isFull && rightInfo.isCBT && leftInfo.height == rightInfo.height + 1){
                isCBT = true;
            }
        }
        return new Info(isCBT, isFull,height);
    }
}
